package cn.icanci.basic;

import com.sun.org.apache.regexp.internal.RE;

import java.sql.*;

/**
 * @Author: icanci
 * @ProjectName: kangaroo-orm
 * @PackageName: cn.icanci.basic
 * @Date: Created in 2020/8/31 13:36
 * @ClassAction: Java操作数据库的5个步骤 贾琏预执事
 * -
 * - 贾：加载驱动
 * - 琏：连接数据库
 * - 预：编写SQL语句、预编译语句/执行语句
 * - 执：执行SQL语句
 * - 事：释放资源
 */
public class TestSelectEmpData {
    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 连接数据库
            conn = DriverManager
                    .getConnection(
                            // 数据库地址
                            "jdbc:mysql://localhost:3306/kangaroo-orm?useSSL=false&serverTimezone=UTC",
                            // 数据库用户名
                            "root",
                            // 数据库密码
                            "root"
                    );
            // 编写SQL语句
            String sql = new String("select * from s_emp").intern();
            // 创建执行SQL的对象
            statement = conn.createStatement();
            // 执行SQL语句 获得结果集
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                // 获取 列名为 id 的值
                int id = resultSet.getInt("id");
                String lastName = resultSet.getString("last_name");
                System.out.println("id:" + id + " , last_name:" + lastName);
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (null != statement){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (null != conn) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
